package com.gy.api.mobile.ykb.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.digital.szzz.gateway.sdk.api.GatewaySender;
import com.digital.szzz.gateway.sdk.bean.GatewayResponse;
import com.gy.api.base.ApiIndex;
import com.gy.api.base.Constants;
import com.gy.api.base.R;
import com.gy.api.base.Type;
import com.gy.api.mobile.company.dao.CompanyInfoDao;
import com.gy.api.mobile.company.domain.po.CompanyInfoPO;
import com.gy.api.mobile.company.service.ICompanyService;
import com.gy.api.mobile.user.dao.MobileUserDao;
import com.gy.api.mobile.user.domain.po.MobileUserPO;
import com.gy.api.mobile.user.service.IUserService;
import com.gy.api.mobile.ykb.domain.YKBCodeVO;
import com.gy.api.mobile.ykb.domain.YKBLoginResVO;
import com.gy.api.mobile.ykb.domain.YKBLoginVO;
import com.gy.api.pc.sys.user.domain.po.SysUserPO;
import com.gy.api.pc.ykz.domain.OapiRpcAuth2UserInfo;
import com.gy.api.pc.ykz.domain.YKZBindVO;
import com.gy.api.pc.ykz.domain.YKZLoginResVO;
import com.gy.api.pc.ykz.domain.YKZLoginVO;
import com.gy.exception.BusinessException;
import com.gy.util.EncryptionUtils;
import com.gy.util.RestTemplateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ykb")
@Api( tags = ApiIndex.YKBUserController)
@Slf4j
public class YKBUserController{

	@Value("${ykb.auth.url}")
	private String url;
	@Value("${ykb.auth.appKey}")
	private String appKey;
	@Value("${ykb.auth.appIv}")
	private String appIv;
	@Value("${ykb.auth.appId}")
	private String appId;
	@Value("${ykb.auth.appSecret}")
	private String appSecret;


	@GetMapping("/getJSAPIToken")
	@ApiOperation(value = "渝快办-获取jsapitoken", notes = "获取jsapitoken")
	public R getJSAPIToken() {
		// todo 加入缓存
		Object jsapiToken = getToken();
		log.info("返回参数jsapiToken:{}", jsapiToken);
		return new R(jsapiToken);
	}

	public static void main(String[] args) {
		JSONObject jsonObject=JSONObject.parseObject("{\"code\":0,\"message\":\"succ\",\"data\":{\"userInfo\":{\"id\":\"10966387720069\",\"userName\":\"rand_pdaedfwmxq\",\"userType\":1,\"phone\":\"15523262786\",\"status\":1,\"userVerification\":{\"status\":2,\"userPersonId\":\"500101199601288646\",\"userPersonName\":\"向元昭\",\"userPersonIdType\":1,\"userPersonIdStart\":\"20231129\",\"userPersonIdEnd\":\"20431129\"},\"userExtend\":{\"deviceId\":\"Zwd9vgv+6ncDAGPla6El5e+a\",\"lastLoginTime\":\"10/10/24 3:13 PM\",\"sex\":0},\"externalInfo\":{\"externalId\":\"70BB14702B2F42A793EC17FA0A427A5A\",\"externalSystem\":\"INSPURE\",\"loginName\":\"rand_pdaedfwmxq\",\"userId\":\"10966387720069\"}}}}");
		System.out.println(jsonObject.toJSONString());
//		System.out.println(jsonObject.getJSONObject("data").toJSONString());
//		System.out.println(jsonObject.getJSONObject("data").getJSONObject("userInfo").toJSONString());
		JSONObject userInfo=jsonObject.getJSONObject("data").getJSONObject("userInfo");
		JSONObject userVerification=userInfo.getJSONObject("userVerification");
		JSONObject userExtend=userInfo.getJSONObject("userExtend");
		String userPhone=userInfo.getString("phone");
		Integer sex=userExtend.getIntValue("sex");
		String userPersonName=userVerification.getString("userPersonName");
		if(userInfo.getIntValue("userType")==1){
			//注册个人用户
			log.info(userPersonName);
			log.info(userPhone);
			log.info(sex+"");
		}else{
			//注册企业用户
			JSONObject org=userInfo.getJSONObject("ogr");
			String orgName=org.getString("orgName");
			String socialCreditCode=org.getString("socialCreditCode");

		}



	}


	@GetMapping("/get_user_info")
	@ApiOperation(value = "渝快办-查询用户信息-会返回gy_token")
	public R<JSONObject> get_user_info(@ModelAttribute YKBCodeVO authCode) {
		JSONObject jsonObject=getUserInfo(authCode.getAuthCode());
//		GatewayResponse response=getUserInfo(authCode.getAuthCode());
//		JSONObject jsonObject=JSONObject.parseObject(response.getData());


//		log.info(response.getCode()+"");
//		log.info(response.getMessage());
//		log.info(response.getData());
//		JSONObject jsonObject=new JSONObject();
		if(jsonObject!=null){
			//{"code":0,"message":"succ","data":{"userInfo":{"id":"10966387720069","userName":"rand_pdaedfwmxq","userType":1,"phone":"15523262786","status":1,"userVerification":{"status":2,"userPersonId":"500101199601288646","userPersonName":"向元昭","userPersonIdType":1,"userPersonIdStart":"20231129","userPersonIdEnd":"20431129"},"userExtend":{"deviceId":"Zwd9vgv+6ncDAGPla6El5e+a","lastLoginTime":"10/10/24 3:13 PM","sex":0},"externalInfo":{"externalId":"70BB14702B2F42A793EC17FA0A427A5A","externalSystem":"INSPURE","loginName":"rand_pdaedfwmxq","userId":"10966387720069"}}}}
//			jsonObject=JSONObject.parseObject(response.getData());

			JSONObject userInfo=jsonObject.getJSONObject("data").getJSONObject("userInfo");
			JSONObject userVerification=userInfo.getJSONObject("userVerification");
			JSONObject userExtend=userInfo.getJSONObject("userExtend");
			String userPhone=userInfo.getString("phone");
			String id=userInfo.getString("id");
			Integer sex=userExtend.getIntValue("sex");
			String userPersonName=userVerification.getString("userPersonName");
			String userPersonId=userVerification.getString("userPersonId");
			if(userInfo.getIntValue("userType")==1){
				//注册个人用户
				Example example=new Example(MobileUserPO.class);
				example.and().andEqualTo("userPhone",userPhone);
				MobileUserPO mobileUserPO=mobileUserDao.selectOneByExample(example);
				if(mobileUserPO==null){
					//注册用户
					mobileUserPO=new MobileUserPO();
					mobileUserPO.setUserName(userPersonName);
					mobileUserPO.setUserSex(sex==1?1:2);
					mobileUserPO.setUseState(1);
					mobileUserPO.setUserCard(userPersonId);
					mobileUserPO.setUserPhone(userPhone);
					mobileUserPO.setYkbId(id);
					mobileUserPO.setLoginName(userPhone);
					String password= RandomUtil.randomString (6);
					mobileUserPO.preInsert();
					mobileUserPO.setLoginPassword(EncryptionUtils.encrypt(mobileUserPO.getId()+password));
					mobileUserDao.insertSelective(mobileUserPO);
				}else{
					mobileUserPO.setUserCard(userPersonId);
					mobileUserPO.setYkbId(id);
					mobileUserPO.preUpdate();
					mobileUserDao.updateByPrimaryKeySelective(mobileUserPO);
				}
				StpUtil.login(mobileUserPO.getId(),"h5_user");
				jsonObject.put("gy_token",StpUtil.getTokenValue());
			}else{
				//注册企业用户
				JSONObject org=userInfo.getJSONObject("org");
				String orgName=org.getString("orgName");
				String socialCreditCode=org.getString("socialCreditCode");

				Example sysExample = new Example(CompanyInfoPO.class);
				sysExample.and().andEqualTo("companyName",orgName)
						.andEqualTo("delFlag", Constants.DEL_FLAG_FALSE);
				CompanyInfoPO companyInfoPO=companyInfoDao.selectOneByExample(sysExample);
				if(companyInfoPO==null){
					sysExample = new Example(CompanyInfoPO.class);
					sysExample.and().andEqualTo("companyCreditCode",socialCreditCode)
							.andEqualTo("delFlag", Constants.DEL_FLAG_FALSE);
					companyInfoPO=companyInfoDao.selectOneByExample(sysExample);

				}
				if(companyInfoPO==null){
					companyInfoPO=new CompanyInfoPO();
					companyInfoPO.setCompanyName(orgName);
					companyInfoPO.setCompanyState(2);
					companyInfoPO.setCompanyCreditCode(socialCreditCode);
					companyInfoPO.setYkbId(id);
					companyInfoPO.setUserCard(userPersonId);
					companyInfoPO.setUserPhone(userPhone);
					companyInfoPO.setUserName(userPersonName);
					String password= RandomUtil.randomString (6);
					companyInfoPO.preInsert();
					companyInfoPO.setLoginPassword(EncryptionUtils.encrypt(companyInfoPO.getId()+password));
					companyInfoDao.insertSelective(companyInfoPO);
				}else{
					companyInfoPO.setUserCard(userPersonId);
					companyInfoPO.setYkbId(id);
					companyInfoPO.preUpdate();
					companyInfoDao.updateByPrimaryKeySelective(companyInfoPO);
				}
				StpUtil.login(companyInfoPO.getId(),"h5_company");
				jsonObject.put("gy_token",StpUtil.getTokenValue());
			}


		}
//		else {
//			return new R(response.getCode(),response.getMessage());
//		}


		return new R(jsonObject);
	}

	@Autowired
	private IUserService userService;
	@Autowired
	private ICompanyService companyService;
	@Autowired
	private MobileUserDao mobileUserDao;
	@Autowired
	private CompanyInfoDao companyInfoDao;


	@ApiOperation(value = "[舍弃]愉快办绑定用户")
	@PostMapping(value = "/bind")
	@ResponseBody
	@SaCheckLogin
	public R bind(@ApiParam(value = "查询参数") @Valid @RequestBody YKZBindVO bindVO, BindingResult bindingResult) {
		if(StringUtils.isBlank(bindVO.getUserId())){
			bindVO.setUserId(StpUtil.getLoginIdAsString());
		}
		CompanyInfoPO companyInfoPO=companyInfoDao.selectByPrimaryKey(bindVO.getUserId());
		MobileUserPO mobileUserPO=mobileUserDao.selectByPrimaryKey(bindVO.getUserId());
		if(companyInfoPO==null&&mobileUserPO==null){
			throw new BusinessException(Type.FAIL.getCode(),"用户信息不存在！");
		}
		if(companyInfoPO!=null){
			companyInfoPO.setYkbId(bindVO.getYkzId());
			companyInfoPO.preUpdate();
			companyInfoDao.updateByPrimaryKeySelective(companyInfoPO);
		}

		if(mobileUserPO!=null){
			mobileUserPO.setYkbId(bindVO.getYkzId());
			mobileUserPO.preUpdate();
			mobileUserDao.updateByPrimaryKeySelective(mobileUserPO);
		}
		return new R();
	}


	@ApiOperation(value = "愉快办授权登陆(返回token代表登陆成功)")
	@PostMapping(value = "/login")
	@ResponseBody
	public R<YKBLoginResVO> login(@ApiParam(value = "查询参数") @Valid @RequestBody YKBLoginVO userLogin, BindingResult bindingResult) {
		YKBLoginResVO ykbLoginResVO=new YKBLoginResVO();

		Example example=new Example(CompanyInfoPO.class);
		example.and().andEqualTo("ykbId",userLogin.getYkbId());
		CompanyInfoPO companyInfoPO=companyInfoDao.selectOneByExample(example);

		Example example1=new Example(MobileUserPO.class);
		example1.and().andEqualTo("ykbId",userLogin.getYkbId());
		MobileUserPO mobileUserPO=mobileUserDao.selectOneByExample(example1);
		if(companyInfoPO!=null){
			StpUtil.login(companyInfoPO.getId(),"h5");
			ykbLoginResVO.setType(1);
			ykbLoginResVO.setToken(StpUtil.getTokenValue());
		}
		if(mobileUserPO!=null){
			StpUtil.login(mobileUserPO.getId(),"h5");
			ykbLoginResVO.setType(2);
			ykbLoginResVO.setToken(StpUtil.getTokenValue());
		}
		return new R().setData(ykbLoginResVO);
	}



	private static String get_token = "http://100.190.0.112:8182/api/getJSAPIToken";
	private static String get_get_user_info = "http://100.190.0.112:8182/api/get_user_info";




	public Object getToken() {
		ResponseEntity responseEntity = RestTemplateUtils.get(get_token, JSONObject.class);
		responseEntity.getStatusCode();
		log.info("getStatusCode::::::::::::" + responseEntity.getStatusCode().toString());
		log.info("getBody::::::::::::" + responseEntity.getBody());
		JSONObject json= (JSONObject) responseEntity.getBody();
		JSONObject data=json.getJSONObject("data");
		return data;
	}

	public JSONObject getUserInfo(String authCode) {
		ResponseEntity responseEntity = RestTemplateUtils.get(get_get_user_info+"?authCode="+authCode, JSONObject.class);
		responseEntity.getStatusCode();
		log.info("getStatusCode::::::::::::" + responseEntity.getStatusCode().toString());
		log.info("getBody::::::::::::" + responseEntity.getBody());
		JSONObject json= (JSONObject) responseEntity.getBody();
		JSONObject data=json.getJSONObject("data");
		return data;
	}

//	/**
//	 * 获取JSAPIToken
//	 *
//	 * @return
//	 */
//	public Object getToken() {
//		String url = this.url; //请求地址
//		String appId = this.appId;// 应用唯一标识
//		String appIv = this.appIv; // app加密偏移量
//		String appKey = this.appKey;//pp加密key
//		String appSecretKey = this.appSecret;//app加密秘钥
//		String authCode = null;// 用户授权令牌传空
//		Integer readTimeout = 2000;//接口读取超时时间 ms
//		Integer connTimeout = 2000;//接口连接超时时间 ms
//		String method = "ykb.app.jsapi.getToken";
//		JSONObject parame = new JSONObject();
//		parame.put("appId", this.appId);
//		Map<String, String> headerMap = new HashMap<>();
//		log.info("调用sdk请求参数req url:{},appId:{}", url, appId);
//		GatewaySender gatewaySender = new GatewaySender();
//		log.info("gatewaySender对象:{}", gatewaySender);
//		GatewayResponse send = GatewaySender.send(url, appId, method, appIv, appKey, appSecretKey, parame, authCode, headerMap, readTimeout, connTimeout);
//		log.info("调用sdk返回参数res:{}", send);
//		return send;
//	}
//
//	public GatewayResponse getUserInfo(String authCode) {
//		String url = this.url; //请求地址
//		String appId = this.appId;// 应用唯一标识
//		String appIv = this.appIv; // app加密偏移量
//		String appKey = this.appKey;//pp加密key
//		String appSecretKey = this.appSecret;//app加密秘钥
////		String authCode = authCode;// 用户授权令牌传空
//		Integer readTimeout = 2000;//接口读取超时时间 ms
//		Integer connTimeout = 2000;//接口连接超时时间 ms
//		String method = "app.ykb.uc.oauth.userInfo";
//		JSONObject parame = new JSONObject();
//		parame.put("authCode", authCode);
//		Map<String, String> headerMap = new HashMap<>();
//		log.info("调用sdk请求参数req url:{},appId:{}", url, appId);
//		GatewaySender gatewaySender = new GatewaySender();
//		log.info("gatewaySender对象:{}", gatewaySender);
//		GatewayResponse send = GatewaySender.send(url, appId, method, appIv, appKey, appSecretKey, parame, authCode, headerMap, readTimeout, connTimeout);
//		log.info("调用sdk返回参数res:{}", send);
//		return send;
//	}


}
